package library.multiple_pictures_selector.ui;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import library.multiple_pictures_selector.R;
import library.multiple_pictures_selector.R2;
import library.multiple_pictures_selector.internal.ui.adapter.AlbumsAdapter;

/**
 * @author Created by qiang.hou on 2018/7/16.
 * @version 1.0
 */
public class AlbumPopWindow extends PopupWindow {
    private AlbumsAdapter albumsAdapter;
    @BindView(R2.id.album_list_view)
    ListView albumListView;

    private AdapterView.OnItemSelectedListener mOnItemSelectedListener;

    @OnClick(R2.id.button_cancel)
    public void onClick(View view) {
        dismiss();
    }

    public AlbumPopWindow(Context context, AlbumsAdapter adapter, AdapterView.OnItemSelectedListener itemClickListener) {
        super(context);
        this.albumsAdapter = adapter;
        this.mOnItemSelectedListener = itemClickListener;
        View contentView = LayoutInflater.from(context).inflate(R.layout.album_pop_window, null);
        ButterKnife.bind(this, contentView);
        setContentView(contentView);
        init();
    }

    private void init() {
        initView();
        initData();
    }

    private void initView() {
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        // 实例化一个ColorDrawable颜色为半透明(半透明遮罩颜色代码#66000000)
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        this.setBackgroundDrawable(dw);
    }

    private void initData() {
        albumListView.setAdapter(albumsAdapter);
        albumListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mOnItemSelectedListener) {
                    mOnItemSelectedListener.onItemSelected(parent, view, position, id);
                }
                dismiss();
            }
        });
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        albumsAdapter.notifyDataSetChanged();
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        super.showAsDropDown(anchor, xoff, yoff);
        albumListView.invalidate();
    }

    public void notifyDataSetChanged() {
        albumsAdapter.notifyDataSetChanged();
    }
}
